package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.FreemarkerService;
import com.heima.file.service.impl.MinIOTemplate;
import com.heima.model.common.dtos.ArticleDto;
import com.heima.model.common.pojos.article.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 陈辉
 * @data 2024 14:10
 */
@Service
public class FreemarkerServiceImpl implements FreemarkerService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinIOTemplate minIOTemplate;
    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 生成文章详情页
     *
     * @param articleDto
     */
    @Override
    @Async   //标记当前方法为线程异步调用
    public void generateDetailHtml(ArticleDto articleDto) {
        try {
            //1. 基于Freemarker合成详情页
            //1.1 准备数据
            String content = articleDto.getContent();
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("content", JSONArray.parseArray(content));
            //1.2 拿到article模版
            Template template = configuration.getTemplate("article.ftl");
            //1.3 将数据合成到模版
            StringWriter writer = new StringWriter();
            template.process(paramMap,writer);
            //2. 将合成好详情页上传到Minio中
            InputStream is = new ByteArrayInputStream(writer.toString().getBytes(StandardCharsets.UTF_8));
            String staticUrl = minIOTemplate.uploadHtmlFile("", articleDto.getId() + ".html", is);
            //3. 将Minio中详情页对应的url回填ap_article表的static_url上
            ApArticle apArticle = new ApArticle();
            apArticle.setId(articleDto.getId());
            apArticle.setStaticUrl(staticUrl);
            apArticleMapper.updateById(apArticle);

            //todo: 同步文章数据到ES索引库

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
